package guigu.UDP;

import org.junit.Test;

import java.io.IOException;
import java.net.*;

/**
 * UDP协议：
 * 1.将数据、源、目的封装成数据包，不需要建立连接
 * 2.每个数据报的大小限制在64k内
 * 3.发送不管对方是否准备好，接收方收到也不确认，故是不可靠的
 *   可以广播发送
 * 4.发送数据结束时无需释放资源，开销小，速度快。
 */
public class UDPTest {
    //发送端
    @Test
    public void test1() throws IOException {
        DatagramSocket socket = new DatagramSocket();


        String str = "我是UDP方式发送的导弹";
        byte[] data = str.getBytes();
        InetAddress inet = InetAddress.getLocalHost();
        DatagramPacket packet = new DatagramPacket(data,0,data.length,inet,9090);
        socket.send(packet);
        socket.close();
    }

    //接收端
    @Test
    public void test2() throws IOException {
        DatagramSocket Socket = new DatagramSocket(9090);
        byte[] buffer = new byte[100];
        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
        Socket.receive(packet);
        System.out.println(new String(packet.getData(),0,packet.getLength()));
        Socket.close();
    }
}
